﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendEMail.aspx.cs" Inherits="CRMWeb.Pages.SendEMail" %>

<!DOCTYPE html>

<html>
<head id="Head1" runat="server">
    <title>Send EMAIL</title>
    <link rel="stylesheet" id="newtheme" type="text/css" href="/EasyUI/Themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="/Css/CrmStyle.css" />
    <script type="text/javascript" src="/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/EasyUI/jquery.easyui.min.js"></script>
    <script src="../tiny_mce/tiny_mce.js"></script>

    <link href="../Css/uploadify.css" rel="stylesheet" />
    <script src="../Scripts/jquery.uploadify.js"></script>
    <script src="/Scripts/ProgressBar.js"></script>
    <script src="../Scripts/jquery.uploadifive.js"></script>
    <link href="../Css/uploadifive.css" rel="stylesheet" />
    <link href="/Css/ProgressStyle.css" rel="stylesheet" />
    <script src="../Scripts/EmailSMSLog.js"></script>
    <style type="text/css">
        body {
            font: 13px Arial, Helvetica, Sans-serif;
        }

        #queue {
            border: 1px solid #E5E5E5;
            height: 40px;
            overflow: auto;
            margin-bottom: 10px;
            padding: 0 3px 3px;
            width: 268px;
        }



        #txtMailMessage_ifr {
            height: 340px;
        }

        #txtMailMessage_tbl {
            height: 100% !important;
        }
    </style>
</head>
<body>
    <form id="sendmail" runat="server">
        <div id="pnlMail" title=" " class="easyui-panel" style="width: auto; height: auto">
            <table style="width: 100%; height: auto">
                <tr>
                    <td colspan="2">
                        <div class="sms_dropdown">
                            <label style="text-align: left">Email Template:</label>
                            <select class="easyui-combotree" id="cmbUc_emailTemp" style="width: 520px;">
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>

                    <td style="text-align: left; width: 60%">
                        <div class="sms_dropdown">
                            <label style="text-align: left">From:</label>
                            <input class="easyui-combobox" id="cmbUc_from" name="EmailId" style="width: 195px;" />
                            <input type="hidden" id="hdnfrompw" runat="server" />
                        </div>
                        <div class="sms_dropdown">
                            <label style="text-align: left">Send To:</label>
                            <select class="easyui-combogrid" id="cmbSendToUc" style="width: 300px; height: 22px;"></select>
                        </div>
                        <div class="fitsem sms_dropdown">
                            <label style="text-align: left">Email Address:</label>
                            <input id="txttomailid" name="txtMailto" type="text" class="easyui-validatebox" style="width: 300px;" onchange="validateEmail($('#txttomailid').val())" />
                            <span id="spnEmail" style="display: none; color: red; font-size: 14px;"><b>*</b> </span>
                        </div>
                        <div class="fitem sms_dropdown">
                            <label style="text-align: left">Subject:</label>
                            <input id="txtSubject" name="txt_sub" type="text" class="easyui-validatebox" style="width: 300px;" />
                        </div>

                    </td>
                    <td style="text-align: left; width: 40%">
                        <div class="fitem sms_dropdown">
                            <label style="width: 100px; text-align: left;">Attachment:</label>
                            <asp:FileUpload ID="file_uploads" runat="server" />
                            <input type="hidden" id="hdnAttachment" runat="server" />
                            <table id="attachedfiles" style="text-align: right"></table>
                        </div>
                        <div class="fitem sms_dropdown" style="clear: both;">
                            <label style="width: 100px; text-align: left">Drag Here:</label>
                            <input id="file_upload" name="file_upload" type="file" style="display: none" multiple="true">
                            <div id="queue" style="margin-left: 4px;"></div>
                            <input type="hidden" id="hdndragfiles" runat="server" />
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div id="divProgressBar" class='dimmer' style="left: 329px; top: 190px;">
                            <table border='0' align='center' cellpadding='0' cellspacing='0' class='progress_tab'>
                                <tr>
                                    <td ondblclick='void(0);' onmouseover='over=true;' onmouseout='over=false;'>&nbsp</td>
                                    <td>&nbsp</td>
                                    <td colspan='4'>&nbsp</td>
                                    <td>&nbsp</td>
                                </tr>
                                <tr>
                                    <td colspan='4'>&nbsp</td>
                                    <td>
                                        <img src='/Media/ajax-loader-blue.gif' alt='' /></td>
                                    <td colspan='4'>&nbsp</td>
                                    <td>Processing</td>
                                </tr>
                                <tr>
                                    <td>&nbsp</td>
                                    <td>&nbsp</td>
                                    <td>&nbsp</td>
                                </tr>
                            </table>
                        </div>
                    </td>
                    <td></td>
                </tr>
            </table>
            <div data-options="region:'center'" style="padding: 5px; height: 65%;" class="emailbox">
                <asp:TextBox ID="txtMailMessage" runat="server" TextMode="MultiLine" Width="100%"></asp:TextBox>
            </div>
            <div data-options="region:'south',border:false" style="text-align: right; padding: 5px; margin-right: 20px;">
                <label id="lblerror" style="font-size: 14px; font-weight: bold; padding-right: 60px; color: red;" runat="server"></label>
                <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="sendEmail();">Send</a>
            </div>
            <asp:ScriptManager ID="sm1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
            <input type="hidden" runat="server" id="hdnEmailOpr" />
            <input type="hidden" id="hdnNodeValInEmailPage" runat="server" />

            <input type="hidden" id="hdnCategoryID" />
        </div>
    </form>
    <script type="text/javascript">

        var OperatorId = '';
        function validateEmail(elementValue) {
            elementValue = elementValue.replace(/,,*/g, ',').replace(/,$/, '').replace(/^,/, '');
            var flag = false;
            var emails = [];
            emails = elementValue.split(',');

            for (i = 0; i < emails.length; i++) {
                var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
                if (emailPattern.test(emails[i]) == true)
                    flag = true;
                else {
                    flag = false;
                    break;
                }
            }

            if (flag == true) {
                $('#spnEmail').hide();
                return true;
            } else {
                $('#spnEmail').show();
                $('#txttomailid').focus();
                return false;
            }

        }
        function IsValidate() {
            var flag = true;
            if ($('#cmbUc_emailTemp').combobox('getValue') == '') {
                $.messager.alert('Morgan CRM', 'Select Email Template ', 'info');
                return flag = false;
            }
            if ($('#cmbUc_from').combobox('getValue') == '') {
                $.messager.alert('Morgan CRM', 'Select From ', 'info');
                return flag = false;
            }
            var bodyContent = tinyMCE.get('txtMailMessage').getContent();
            bodyContent = $(bodyContent).text().trim();

            if (bodyContent.length == 0) {
                $.messager.alert('Morgan CRM', 'E-Mail content is Empty ! ', 'info');
                return false;
            }
            if (!validateEmail($('#txttomailid').val())) {
                $.messager.alert('Morgan CRM', '<span style="color:red">Enter Vaild Email Address </span>', 'info');
                return;
            }
            if ($('#txtSubject').val() == '') {
                $.messager.alert('Morgan CRM', 'Enter Subject ', 'info');
                return flag = false;
            }

            return flag;
        }

        tinyMCE.init({
            mode: "textareas",
            elements: "txtMailMessage",
            theme: "advanced",
            relative_urls: true,
            remove_script_host: false,
            convert_urls: true,
            plugins: "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
            theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,help,code,|,forecolor,backcolor",
            setup: function (ed) {
                ed.onInit.add(function (ed) {
                    ed.getDoc().body.style.fontSize = '13pt';
                });
            }
        });
        window.onresize = function () {
            $('#pnlMail').panel('resize', {
                width: window.innerWidth,
                height: window.innerHeight
            });
        }


        $(document).ready(function () {
            $('#newtheme').attr('href', '/EasyUI/Themes/' + getQuerystring('Theme', 'Default') + '/easyui.css');

            FetchFullName();
            $("#pnlMail").panel('setTitle', 'Send E-Mail ');
            $('#txttomailid').val(getQuerystring('email', ''));
            $("#cmbSendToUc").combogrid('setValue', getQuerystring('email', ''));
            OperatorId = document.getElementById('hdnNodeValInEmailPage').value;

            $('#cmbUc_emailTemp').combotree({
                onClick: function (node) {
                    if (!$('#cmbUc_emailTemp').tree('isLeaf', node.target)) {
                        $('#cmbUc_emailTemp').combotree('setValues', '');
                        var t = $('#cmbUc_emailTemp').combotree('tree');
                        t.tree('toggle', node.target);
                        var p = $('#cmbUc_emailTemp').combotree('panel');
                        p.panel('open');
                    }
                }
            });
            $('#cmbSendToUc').combogrid({
                url: '/WebServices/SelectAppAndContacts.ashx?app_id=' + getQuerystring('app_id', '') + '&ContactID=' + getQuerystring('contact_id', ''),
                panelWidth: 300,
                multiple: true,
                idField: 'MailID',
                textField: 'FullName',
                editable: true,
                columns: [[
                    { field: 'ck', checkbox: true },
                    { field: 'FullName', width: 40 },
                    { field: 'MailID', width: 70 },
                ]],
                onSelect: getSelectionsForEmail,
                onUnselect: getUnselectForEmail,
                fitColumns: true,
            });

            $('#cmbUc_from').combobox({
                url: '/WebServices/EmailTemplate.ashx?method=SelectAllEmailId&Company=' + getQuerystring('company', ''),
                panelWidth: 200,
                valueField: 'emailaccount',
                textField: 'emailaccount',
                multiple: false,
                editable: false,
                selected: true,
                onSelect: getEmailAccountPassword,
                onLoadSuccess: function (data) {
                    $(this).combobox('select', data[0]['emailaccount']);
                }
            });

            // Wade 20140204 insert onselect:getPwd above
            $('#cmbUc_emailTemp').combotree({
                url: '/WebServices/EmailTemplate.ashx?method=DisplayTemplateNodeForDialog&Company=' + getQuerystring('company', ''),
                onSelect: selectEmailTemplate
            });

            $('#pnlMail').panel('resize', {
                width: window.innerWidth,
                height: window.innerHeight
            });
            $('#cmbUc_emailTemp').combobox('textbox').bind('click', function () {
                $('#cmbUc_emailTemp').combobox('showPanel');
            });
            $('#cmbUc_from').combobox('textbox').bind('click', function () {
                $('#cmbUc_from').combobox('showPanel');
            });
            $('#cmbSendToUc').combobox('textbox').bind('click', function () {
                $('#cmbSendToUc').combobox('showPanel');
            });
        });

        function getSelectionsForEmail() {
            var ss = [];
            var r = $('#cmbSendToUc').combogrid('grid');
            var rows = r.datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                ss.push(row.MailID);
            }

            $("#txttomailid").val(ss.join(','));
        }
        function getUnselectForEmail() {
            $("#txttomailid").val('');
            getSelectionsForEmail();
        }

        $(window).load(
            $(function () {
                $("#file_uploads").uploadify({
                    'swf': '../Media/uploadify.swf',
                    'uploader': '/WebServices/AttachmentUpload.ashx',
                    'cancelImg': '../Media/cancel.png',
                    'fileSizeLimit': '25MB',
                    'buttonText': 'Attach Files',
                    'fileTypeExts': '*.jpg;*.jpeg;*.gif;*.png;*.txt;*.pdf',
                    'fileDesc': 'Image Files',
                    'multi': true,
                    'auto': true,
                    'onUploadComplete': function (file) {
                        var attchVal = fileName;
                        $("#hdnAttachment").val(attchVal);
                    }
                });
            })
        );
        //Wade 20140204
        function getEmailAccountPassword(rec) {
            //  alert(rec.Password);
            $('#hdnfrompw').val(rec.Password);
        }
        //Wade

        //Drag and drop
        $(function () {
            $('#file_upload').uploadifive({
                'auto': true,
                'queueID': 'queue',
                'fileSizeLimit': '25MB',
                'uploadScript': '/WebServices/Upload.ashx',
                'onUploadComplete': function (file, data) {
                    $("#hdndragfiles").val(data);
                }
            });
        });


        function onSuccess() {
            $("#txttomailid").val('');
            $("#cmbUc_from").val('');
            $("#txtSubject").val('');
            tinymce.get('txtMailMessage').setContent('');
            window.opener.location.reload(true);
            window.close();
        }

        //Send Email Function
        function sendEmail() {
            if (IsValidate()) {
                //wade 20140204 comment the following line
                var password = $('#hdnfrompw').val();
                if (password == null) {
                    $.messager.alert('Morgan CRM', 'Oops your password is not found!');
                    HideProgressBarEvent();
                }
                else {
                    DisplayProgessBarEvent();
                    var fromName = $("#cmbUc_from").combobox('getText');
                    var toName = $("#txttomailid").val().replace(/,,*/g, ',').replace(/,$/, '').replace(/^,/, '');
                    var attachmentFile = $("#hdnAttachment").val();
                    var attachmentsDrag = $("#hdndragfiles").val();
                    var subject = $("#txtSubject").val();
                    var bodyContent = tinyMCE.get('txtMailMessage').getContent({ format: 'raw' });

                    $.ajax({
                        type: "Post",
                        data: { fromName: fromName, password: password, toName: toName, attachmentFile: attachmentFile, attachmentsDrag: attachmentsDrag, subject: subject, bodyContent: bodyContent },
                        url: "/WebServices/SendEmailToUsers.ashx",
                        success: function (data) {
                            if (data == '0') {
                                $.messager.alert('Morgan CRM', '<span style="color:red"> Error occured While sending E Mail</span>');
                                // Write Log File
                                writeLog(bodyContent, 'Email', 'Failed', document.getElementById("hdnEmailOpr").value, $('#hdnCategoryID').val());
                            }
                            else if (data == '1') {
                                $.messager.alert('Morgan CRM', '<span style="color:red">Sending Failed ! Invalid SMTP setting </span>');
                                // Write Log File
                                writeLog(bodyContent, 'Email', 'Failed', document.getElementById("hdnEmailOpr").value, $('#hdnCategoryID').val());
                            }
                            else {
                                // Write Log File
                                writeLog(bodyContent, 'Email', 'Success', document.getElementById("hdnEmailOpr").value, $('#hdnCategoryID').val());
                                document.getElementById("attachedfiles").innerHTML = '';
                                document.getElementById("queue").innerHTML = '';
                                UpdateHistory(data);
                            }
                            HideProgressBarEvent();

                        }
                    });
                }
            }
        }



        function UpdateHistory(attachmentlist) {

            var ContactID = getQuerystring('contact_id', 0);
            var AppID = getQuerystring("app_id", 0);
            var currentDate = new Date()

            var HistoryDate = (currentDate.getMonth() + 1) + "/" + currentDate.getDate() + "/" + currentDate.getFullYear();
            var currentTime = new Date()

            var HistoryTime = currentTime.getHours() + ':' + currentTime.getMinutes() + ':' + currentTime.getSeconds();;
            var Action = 'Email_Sent';
            var Operator = document.getElementById('hdnEmailOpr').value;

            var toName = $("#txttomailid").val().replace(/,,*/g, ',').replace(/,$/, '').replace(/^,/, '');

            var emailTxtVal = tinyMCE.get('txtMailMessage').getContent({ format: 'raw' });

            var ColVals = '';
            if (attachmentlist.length > 0) {
                attachmentlist = attachmentlist.replace(/,$/, '');
                ColVals = "To: " + toName + '</br>' + "<span style=\"color:red;font-weight:bold\"> </br>Attachments:-  " + attachmentlist + " </span> </br> Email Content :-" + emailTxtVal;
            }
            else
                ColVals = "To: " + toName + '</br> Email Content :-' + emailTxtVal;


            var desc = encodeURIComponent(ColVals);

            if (AppID > 0) {

                PageMethods.saveNewHistory('Application', '0', HistoryDate, HistoryTime, Action, Operator, desc, AppID);
                setTimeout(function () {
                    onSuccess();
                }, 100);
            }
            else if (ContactID > 0) {
                PageMethods.saveNewHistory('Contact', ContactID, HistoryDate, HistoryTime, Action, Operator, desc, '0');
                setTimeout(function () {
                    onSuccess();
                }, 100);
            }
            else
                onSuccess();
        }

        function getQuerystring(key, defaultValue) {
            if (defaultValue == null) defaultValue = "";
            key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
            var qs = regex.exec(window.location.href);

            if (qs == null || qs == 'null')
                return defaultValue;
            else {
                if (qs[1] == 'null' || qs[1] == null)
                    return defaultValue;
                else
                    return qs[1];
            }
        }


        function FetchFullName() {

            $.ajax({
                url: "/WebServices/SMSHandler.ashx?method=getEmailwithFullName",
                data: { 'app_id': getQuerystring('app_id', ''), 'ContactID': getQuerystring('contact_id', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        $("#pnlMail").panel('setTitle', 'Send E-Mail ' + rec.FullName);
                        $('#txttomailid').val(rec.Email);
                        $('#cmbSendToUc').combogrid('setValue', rec.Email);
                    });
                }
            });
        }

        function selectEmailTemplate(node) {

            var currentTemplateId = node.id;
            if (currentTemplateId == -1) {
                $.messager.alert('Morgan CRM', 'Please select Template Item ... !', 'warning');
            }
            else {
                $.ajax({
                    url: "/WebServices/EmailTemplate.ashx?method=GetEmailTemplateContentById",
                    contentType: "application/json; charset=utf-8",
                    data: { EmailTemplateId: currentTemplateId },
                    success: function (data) {
                        $.each(eval(data.replace(/[\r\n]/, '')), function (i, result) {
                            if (getQuerystring('contact_id', '') != '') {
                                showContactData(result.TemplateFormat);
                            }
                            else if (getQuerystring('app_id', '') != '') {
                                showApplicationData(result.TemplateFormat);
                            }
                            else {
                                tinymce.get('txtMailMessage').setContent(decodeURIComponent(result.TemplateFormat));
                            }
                            $('#txtSubject').val(result.emailsubject);
                            $('#hdnCategoryID').val(result.CategoryId);
                        });
                    },
                    error: function () {
                        alert("Error while getting template.");
                    }
                });
            }
        }

        function showContactData(EMAILTemplateFormat) {
            $.ajax({
                url: "/WebServices/ApplicationContact.ashx?method=ApplicationContactSelect",
                contentType: "application/json; charset=utf-8",
                data: { 'ContactID': getQuerystring('contact_id', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        var decodeTemp = decodeURIComponent(EMAILTemplateFormat);

                        //ClientFileds
                        decodeTemp = decodeTemp.replace('%ContactID (Client)%', rec.ContactID);
                        decodeTemp = decodeTemp.replace('%FirstName (Client)%', rec.FirstName);
                        decodeTemp = decodeTemp.replace('%MiddleName (Client)%', rec.MiddleName);
                        decodeTemp = decodeTemp.replace('%SurName (Client)%', rec.SurName);
                        decodeTemp = decodeTemp.replace('%Title (Client)%', rec.Title);
                        decodeTemp = decodeTemp.replace('%Mobile (Client)%', rec.Mobile);
                        decodeTemp = decodeTemp.replace('%HomePhone (Client)%', rec.HomePhone);
                        decodeTemp = decodeTemp.replace('%Email (Client)%', rec.Email);
                        decodeTemp = decodeTemp.replace('%DriverLicense (Client)%', rec.DriverLicense);
                        decodeTemp = decodeTemp.replace('%Citizenship (Client)%', rec.Citizenship);
                        decodeTemp = decodeTemp.replace('%DateBirth (Client)%', rec.DateBirth);
                        decodeTemp = decodeTemp.replace('%Street (Client)%', rec.Street);
                        decodeTemp = decodeTemp.replace('%Suburb (Client)%', rec.Suburb);
                        decodeTemp = decodeTemp.replace('%State (Client)%', rec.State);
                        decodeTemp = decodeTemp.replace('%PostCode (Client)%', rec.PostCode);
                        decodeTemp = decodeTemp.replace('%ResidencePeriod (Client)%', rec.ResidencePeriod);
                        decodeTemp = decodeTemp.replace('%ResidenceLength (Client)%', rec.ResidenceLength);
                        decodeTemp = decodeTemp.replace('%Dependant (Client)%', rec.Dependant);
                        decodeTemp = decodeTemp.replace('%app_ResidentialStatus (Client)%', rec.app_ResidentialStatus);
                        decodeTemp = decodeTemp.replace('%app_number (Client)%', rec.app_number);
                        decodeTemp = decodeTemp.replace('%app_id (Client)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%NumberFromAppinfo (Client)%', rec.NumberFromAppinfo);
                        decodeTemp = decodeTemp.replace('%Memo (Client)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%CreateDate (Client)%', rec.CreateDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Client)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%DupwithContact (Client)%', rec.DupwithContact);
                        decodeTemp = decodeTemp.replace('%deletedFlag (Client)%', rec.deletedFlag);
                        decodeTemp = decodeTemp.replace('%Role (Client)%', rec.Role);
                        decodeTemp = decodeTemp.replace('%Relationship (Client)%', rec.Relationship);
                        decodeTemp = decodeTemp.replace('%WorkPhone (Client)%', rec.WorkPhone);
                        decodeTemp = decodeTemp.replace('%FaxNumber (Client)%', rec.FaxNumber);
                        decodeTemp = decodeTemp.replace('%secondEmailAddress (Client)%', rec.secondEmailAddress);
                        decodeTemp = decodeTemp.replace('%PostalAddress (Client)%', rec.PostalAddress);
                        decodeTemp = decodeTemp.replace('%IncomeType (Client)%', rec.IncomeType);
                        decodeTemp = decodeTemp.replace('%SelfEmpTypeofEntity (Client)%', rec.SelfEmpTypeofEntity);
                        decodeTemp = decodeTemp.replace('%SelfEmpBusinessName (Client)%', rec.SelfEmpBusinessName);
                        decodeTemp = decodeTemp.replace('%SelfEmpABN (Client)%', rec.SelfEmpABN);
                        decodeTemp = decodeTemp.replace('%SelfEmpNatureofBusiness (Client)%', rec.SelfEmpNatureofBusiness);
                        decodeTemp = decodeTemp.replace('%SelfEmpPhone (Client)%', rec.SelfEmpPhone);
                        decodeTemp = decodeTemp.replace('%SelfEmpAddress (Client)%', rec.SelfEmpAddress);
                        decodeTemp = decodeTemp.replace('%KinsName (Client)%', rec.KinsName);
                        decodeTemp = decodeTemp.replace('%KinsRelationship (Client)%', rec.KinsRelationship);
                        decodeTemp = decodeTemp.replace('%KinsContactNumber (Client)%', rec.KinsContactNumber);
                        decodeTemp = decodeTemp.replace('%Notes (Client)%', rec.Notes);
                        decodeTemp = decodeTemp.replace('%EmpEmployer (Client)%', rec.EmpEmployer);
                        decodeTemp = decodeTemp.replace('%EmpOccupation (Client)%', rec.EmpOccupation);
                        decodeTemp = decodeTemp.replace('%EmpJobPosition (Client)%', rec.EmpJobPosition);
                        decodeTemp = decodeTemp.replace('%EmpEmployerPhone (Client)%', rec.EmpEmployerPhone);
                        decodeTemp = decodeTemp.replace('%EmpContactPerson (Client)%', rec.EmpContactPerson);
                        decodeTemp = decodeTemp.replace('%EmpWorkAddress (Client)%', rec.EmpWorkAddress);
                        decodeTemp = decodeTemp.replace('%comesfrom (Client)%', rec.comesfrom);

                        //Loan Fileds
                        decodeTemp = decodeTemp.replace('%LoanID (Loan)%', rec.LoanID);
                        decodeTemp = decodeTemp.replace('%LoanNumber (Loan)%', rec.LoanNumber);
                        decodeTemp = decodeTemp.replace('%PaymentPeriod (Loan)%', rec.PaymentPeriod);
                        decodeTemp = decodeTemp.replace('%DrawDownDate (Loan)%', rec.DrawDownDate);
                        decodeTemp = decodeTemp.replace('%LoanStatusID (Loan)%', rec.LoanStatusID);
                        decodeTemp = decodeTemp.replace('%LoanTerm (Loan)%', rec.LoanTerm);
                        decodeTemp = decodeTemp.replace('%FirstPaymentDue (Loan)%', rec.FirstPaymentDue);
                        decodeTemp = decodeTemp.replace('%LowerRate (Loan)%', rec.LowerRate);
                        decodeTemp = decodeTemp.replace('%HigherRate (Loan)%', rec.HigherRate);
                        decodeTemp = decodeTemp.replace('%InterestMethod (Loan)%', rec.InterestMethod);
                        decodeTemp = decodeTemp.replace('%app_id (Loan)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%Lender (Loan)%', rec.Lender);
                        decodeTemp = decodeTemp.replace('%Product (Loan)%', rec.Product);
                        decodeTemp = decodeTemp.replace('%Type (Loan)%', rec.Type);
                        decodeTemp = decodeTemp.replace('%Purpose (Loan)%', rec.Purpose);
                        decodeTemp = decodeTemp.replace('%LoanAmount (Loan)%', rec.LoanAmount);
                        decodeTemp = decodeTemp.replace('%DishonorFee (Loan)%', rec.DishonorFee);
                        decodeTemp = decodeTemp.replace('%Memo (Loan)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%NewDDRDate (Loan)%', rec.NewDDRDate);
                        decodeTemp = decodeTemp.replace('%BankAccDate (Loan)%', rec.BankAccDate);
                        decodeTemp = decodeTemp.replace('%PaymentSchDate (Loan)%', rec.PaymentSchDate);
                        decodeTemp = decodeTemp.replace('%EffectiveDate (Loan)%', rec.EffectiveDate);
                        decodeTemp = decodeTemp.replace('%DefaultNotice (Loan)%', rec.DefaultNotice);
                        decodeTemp = decodeTemp.replace('%DoubleChecked (Loan)%', rec.DoubleChecked);
                        decodeTemp = decodeTemp.replace('%CreateDate (Loan)%', rec.CreateDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Loan)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%LastResult (Loan)%', rec.LastResult);
                        decodeTemp = decodeTemp.replace('%EzidebitRefNo (Loan)%', rec.EzidebitRefNo);
                        decodeTemp = decodeTemp.replace('%OperatorName%', document.getElementById('hdnEmailOpr').value);
                        tinymce.get('txtMailMessage').setContent(decodeTemp);
                    });
                }
            });
        }

        var FsName = [];
        var MidName = [];
        var LastName = [];
        var strFsName;
        var strMidName;
        var strLsName;
        function showApplicationData(EMAILTemplateFormat) {
            $.ajax({
                url: "/WebServices/ApplicationProfileDataSelect.ashx",
                contentType: "application/json; charset=utf-8",
                data: { 'app_id': getQuerystring('app_id', ''), 'OperatorId': OperatorId },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        var decodeTemp = decodeURIComponent(EMAILTemplateFormat);

                        //ApplicationFileds
                        decodeTemp = decodeTemp.replace('%app_id (Application)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%deletedFlag (Application)%', rec.deletedFlag);
                        decodeTemp = decodeTemp.replace('%app_result (Application)%', rec.app_result);
                        decodeTemp = decodeTemp.replace('%ResultID (Application)%', rec.ResultID);
                        decodeTemp = decodeTemp.replace('%LoadNo (Application)%', rec.LoadNo);
                        decodeTemp = decodeTemp.replace('%Folder (Application)%', rec.Folder);
                        decodeTemp = decodeTemp.replace('%AwaitDocs (Application)%', rec.AwaitDocs);
                        decodeTemp = decodeTemp.replace('%NoInApplication (Application)%', rec.NoInApplication);
                        decodeTemp = decodeTemp.replace('%OfferedAmount (Application)%', rec.OfferedAmount);
                        decodeTemp = decodeTemp.replace('%DesiredAmount (Application)%', rec.DesiredAmount);
                        decodeTemp = decodeTemp.replace('%amountMoto (Application)%', rec.amountMoto);
                        decodeTemp = decodeTemp.replace('%amoutProperties (Application)%', rec.amoutProperties);
                        decodeTemp = decodeTemp.replace('%TextAwaitDoc (Application)%', rec.TextAwaitDoc);
                        decodeTemp = decodeTemp.replace('%PurposeSummary (Application)%', rec.PurposeSummary);
                        // decodeTemp = decodeTemp.replace('%Unsubscribe_Ad (Application)%', rec.Unsubscribe_Ad);
                        decodeTemp = decodeTemp.replace('%Memo (Application)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%LenderID (Application)%', rec.LenderID);
                        decodeTemp = decodeTemp.replace('%OutSrcLenderVal (Application)%', rec.OutSrcLenderVal);
                        decodeTemp = decodeTemp.replace('%ReferrerID (Application)%', rec.ReferrerID);
                        decodeTemp = decodeTemp.replace('%ReferrerVal (Application)%', rec.ReferrerVal);
                        decodeTemp = decodeTemp.replace('%CreatedDate (Application)%', rec.CreatedDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Application)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%comesfrom (Application)%', rec.comesfrom);
                        decodeTemp = decodeTemp.replace('%securities (Application)%', rec.securities);

                        //ClientFileds
                        decodeTemp = decodeTemp.replace('%ContactID (Client)%', rec.ContactID);

                        //First applicant name:
                        FsName.push(rec.FirstName);
                        strFsName = FsName[0];
                        decodeTemp = decodeTemp.replace('%FirstName (Client)%', strFsName);


                        MidName.push(rec.MiddleName);
                        strMidName = MidName[0];
                        decodeTemp = decodeTemp.replace('%MiddleName (Client)%', strMidName);

                        LastName.push(rec.SurName);
                        strLsName = LastName[0];
                        decodeTemp = decodeTemp.replace('%SurName (Client)%', strLsName);

                        decodeTemp = decodeTemp.replace('%Title (Client)%', rec.Title);
                        decodeTemp = decodeTemp.replace('%Mobile (Client)%', rec.Mobile);
                        decodeTemp = decodeTemp.replace('%HomePhone (Client)%', rec.HomePhone);
                        decodeTemp = decodeTemp.replace('%Email (Client)%', rec.Email);
                        decodeTemp = decodeTemp.replace('%DriverLicense (Client)%', rec.DriverLicense);
                        decodeTemp = decodeTemp.replace('%Citizenship (Client)%', rec.Citizenship);
                        decodeTemp = decodeTemp.replace('%DateBirth (Client)%', rec.DateBirth);
                        decodeTemp = decodeTemp.replace('%Street (Client)%', rec.Street);
                        decodeTemp = decodeTemp.replace('%Suburb (Client)%', rec.Suburb);
                        decodeTemp = decodeTemp.replace('%State (Client)%', rec.State);
                        decodeTemp = decodeTemp.replace('%PostCode (Client)%', rec.PostCode);
                        decodeTemp = decodeTemp.replace('%ResidencePeriod (Client)%', rec.ResidencePeriod);
                        decodeTemp = decodeTemp.replace('%ResidenceLength (Client)%', rec.ResidenceLength);
                        decodeTemp = decodeTemp.replace('%Unsubscribe_Ad (Client)%', rec.Unsubscribe_Ad);
                        decodeTemp = decodeTemp.replace('%Dependant (Client)%', rec.Dependant);
                        decodeTemp = decodeTemp.replace('%app_ResidentialStatus (Client)%', rec.app_ResidentialStatus);
                        decodeTemp = decodeTemp.replace('%app_number (Client)%', rec.app_number);
                        decodeTemp = decodeTemp.replace('%app_id (Client)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%NumberFromAppinfo (Client)%', rec.NumberFromAppinfo);
                        decodeTemp = decodeTemp.replace('%Memo (Client)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%CreateDate (Client)%', rec.CreateDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Client)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%DupwithContact (Client)%', rec.DupwithContact);
                        decodeTemp = decodeTemp.replace('%deletedFlag (Client)%', rec.deletedFlag);
                        decodeTemp = decodeTemp.replace('%Role (Client)%', rec.Role);
                        decodeTemp = decodeTemp.replace('%Relationship (Client)%', rec.Relationship);
                        decodeTemp = decodeTemp.replace('%WorkPhone (Client)%', rec.WorkPhone);
                        decodeTemp = decodeTemp.replace('%FaxNumber (Client)%', rec.FaxNumber);
                        decodeTemp = decodeTemp.replace('%secondEmailAddress (Client)%', rec.secondEmailAddress);
                        decodeTemp = decodeTemp.replace('%PostalAddress (Client)%', rec.PostalAddress);
                        decodeTemp = decodeTemp.replace('%IncomeType (Client)%', rec.IncomeType);
                        decodeTemp = decodeTemp.replace('%SelfEmpTypeofEntity (Client)%', rec.SelfEmpTypeofEntity);
                        decodeTemp = decodeTemp.replace('%SelfEmpBusinessName (Client)%', rec.SelfEmpBusinessName);
                        decodeTemp = decodeTemp.replace('%SelfEmpABN (Client)%', rec.SelfEmpABN);
                        decodeTemp = decodeTemp.replace('%SelfEmpNatureofBusiness (Client)%', rec.SelfEmpNatureofBusiness);
                        decodeTemp = decodeTemp.replace('%SelfEmpPhone (Client)%', rec.SelfEmpPhone);
                        decodeTemp = decodeTemp.replace('%SelfEmpAddress (Client)%', rec.SelfEmpAddress);
                        decodeTemp = decodeTemp.replace('%KinsName (Client)%', rec.KinsName);
                        decodeTemp = decodeTemp.replace('%KinsRelationship (Client)%', rec.KinsRelationship);
                        decodeTemp = decodeTemp.replace('%KinsContactNumber (Client)%', rec.KinsContactNumber);
                        decodeTemp = decodeTemp.replace('%Notes (Client)%', rec.Notes);
                        decodeTemp = decodeTemp.replace('%EmpEmployer (Client)%', rec.EmpEmployer);
                        decodeTemp = decodeTemp.replace('%EmpOccupation (Client)%', rec.EmpOccupation);
                        decodeTemp = decodeTemp.replace('%EmpJobPosition (Client)%', rec.EmpJobPosition);
                        decodeTemp = decodeTemp.replace('%EmpEmployerPhone (Client)%', rec.EmpEmployerPhone);
                        decodeTemp = decodeTemp.replace('%EmpContactPerson (Client)%', rec.EmpContactPerson);
                        decodeTemp = decodeTemp.replace('%EmpWorkAddress (Client)%', rec.EmpWorkAddress);
                        decodeTemp = decodeTemp.replace('%comesfrom (Client)%', rec.comesfrom);

                        //Loan Fileds
                        decodeTemp = decodeTemp.replace('%LoanID (Loan)%', rec.LoanID);
                        decodeTemp = decodeTemp.replace('%LoanNumber (Loan)%', rec.LoanNumber);
                        decodeTemp = decodeTemp.replace('%PaymentPeriod (Loan)%', rec.PaymentPeriod);
                        decodeTemp = decodeTemp.replace('%DrawDownDate (Loan)%', rec.DrawDownDate);
                        decodeTemp = decodeTemp.replace('%LoanStatusID (Loan)%', rec.LoanStatusID);
                        decodeTemp = decodeTemp.replace('%LoanTerm (Loan)%', rec.LoanTerm);
                        decodeTemp = decodeTemp.replace('%FirstPaymentDue (Loan)%', rec.FirstPaymentDue);
                        decodeTemp = decodeTemp.replace('%LowerRate (Loan)%', rec.LowerRate);
                        decodeTemp = decodeTemp.replace('%HigherRate (Loan)%', rec.HigherRate);
                        decodeTemp = decodeTemp.replace('%InterestMethod (Loan)%', rec.InterestMethod);
                        decodeTemp = decodeTemp.replace('%app_id (Loan)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%Lender (Loan)%', rec.Lender);
                        decodeTemp = decodeTemp.replace('%Product (Loan)%', rec.Product);
                        decodeTemp = decodeTemp.replace('%Type (Loan)%', rec.Type);
                        decodeTemp = decodeTemp.replace('%Purpose (Loan)%', rec.Purpose);
                        decodeTemp = decodeTemp.replace('%LoanAmount (Loan)%', rec.LoanAmount);
                        decodeTemp = decodeTemp.replace('%DishonorFee (Loan)%', rec.DishonorFee);
                        decodeTemp = decodeTemp.replace('%Memo (Loan)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%NewDDRDate (Loan)%', rec.NewDDRDate);
                        decodeTemp = decodeTemp.replace('%BankAccDate (Loan)%', rec.BankAccDate);
                        decodeTemp = decodeTemp.replace('%PaymentSchDate (Loan)%', rec.PaymentSchDate);
                        decodeTemp = decodeTemp.replace('%EffectiveDate (Loan)%', rec.EffectiveDate);
                        decodeTemp = decodeTemp.replace('%DefaultNotice (Loan)%', rec.DefaultNotice);
                        decodeTemp = decodeTemp.replace('%DoubleChecked (Loan)%', rec.DoubleChecked);
                        decodeTemp = decodeTemp.replace('%CreateDate (Loan)%', rec.CreateDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Loan)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%LastResult (Loan)%', rec.LastResult);
                        decodeTemp = decodeTemp.replace('%EzidebitRefNo (Loan)%', rec.EzidebitRefNo);
                        decodeTemp = decodeTemp.replace('%OperatorName%', document.getElementById('hdnEmailOpr').value);
                        tinymce.get('txtMailMessage').setContent(decodeTemp);
                    });
                }
            });
        }

    </script>
</body>
</html>
